/**
 * @file 工单列表
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/11/27 10:20:40
 */

layui.define(['element', 'layer', 'form', 'table', 'zmnTable', 'formSelects', 'zmnSearch', 'lodash', 'select2', 'searchPage'], function (exports) {
    var $ = layui.$;
    var table = layui.table;
    var zmnTable = layui.zmnTable;
    var element = layui.element;
    // 当前操作的工单
    window.currentWork = {};

    /**
     * 通话记录
     * @type {Array[]|Array}
     */
    var callRecordListContainer = callRecordList || [];

    /**
     * 工程师上门录音
     * @type {[[]]|*[]}
     */
    var workingRecordListContainer = workingRecordList || [];

    /**
     * 通话记录tab id
     * @type {string}
     */
    var CALL_RECORD_LIST_TABLE_ID = 'callRecordListTable';

    /**
     * 未完成跟单
     */
    function renderCallRecordListTable(callRecordList) {
        table.render({
            elem: '#' + CALL_RECORD_LIST_TABLE_ID,
            limit: 10000,
            cols: [
                [
                    {field: 'typeName', title: '通话类型', width: 160},
                    {field: 'callRecordId', title: '通话记录ID'},
                    {field: 'callerNo', title: '主叫'},
                    {field: 'xnoNo', title: '小号'},
                    {field: 'calledNo', title: '被叫'},
                    {field: 'connect', title: '接通'},
                    {field: 'answer', title: '接听'},
                    {field: 'startTime', title: '通话开始时间'},
                    {field: 'finishTime', title: '通话结束时间'},
                    {field: 'callDuration', title: '通话时长'},
                    {field: 'hangup', title: '挂断方'},
                    {field: 'finishState', title: '挂机原因'},
                    {field: 'tapeUrl', title: '录音', templet: '#play-btn'},
                    {
                        title: '下载',
                        width: '10%',
                        toolbar: '#downloadMenu'
                    }
                ]
            ],
            data: callRecordList
        });
    }

    var util = layui.util;

    function renderWorkingRecordListTable(workingRecordList) {
        table.render({
            elem: '#workingRecordListTable',
            limit: 10000,
            cols: [
                [
                    {field: 'recordNodeName', title: '录音节点', width: 160},
                    {field: 'recordId', title: '录音记录ID'},
                    {field: 'recordStatusName', title: '录音状态'},
                    {field: 'detectionResultStr', title: '质检结果'},
                    {field: 'recordDurationStr', title: '录音时长'},
                    {
                        field: 'recordStartTime', title: '录音开始时间', templet: function (d) {
                            return util.toDateString(d.recordStartTime, "yyyy-MM-dd HH:mm:ss")
                        }
                    },
                    {
                        field: 'recordEndTime', title: '录音结束时间', templet: function (d) {
                            return util.toDateString(d.recordEndTime, "yyyy-MM-dd HH:mm:ss")
                        }
                    },
                    {field: 'engineerNamePhone', title: '工程师'},
                    {field: 'recordUrl', title: '录音', templet: '#playRecordTpl'},
                    {field: 'recordUrl', title: '下载', templet: '#dowonloadFileTpl'},
                ]
            ],
            data: workingRecordList
        });
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {
        $('.layui-card-body').on('click', '.play-btn', function (e) {
            let src = e.currentTarget.dataset.src;
            playRecord(src);
        });

        $('.layui-card-body').on('click', '.play-record-btn', function (e) {
            let src = e.currentTarget.dataset.src;
            playRecordWork(src);
        });
    }

    function playRecordWork(src) {
        layer.open({
            title: '录音详情',
            shadeClose: true,
            content: `<audio src="${src}" controls autoplay controlslist="nodownload" oncontextmenu="return false"></audio>`
        });
    }

    function playRecord(src) {
        layer.open({
            title: '录音详情',
            shadeClose: true,
            content: `<audio src="${src}" controls autoplay></audio>`
        });
    }

    table.on('tool(callrecord-table)', function (obj) {

        if (obj.event === 'downloadRecordEvent') {
            var filePath = obj.data.recordUrl;
            var recordId = obj.data.recordId;
            axios({
                method: 'get',
                url: filePath,
                // 必须显式指明响应类型是一个Blob对象，这样生成二进制的数据，才能通过window.URL.createObjectURL进行创建成功
                responseType: 'blob',
            }).then((res) => {
                if (!res) {
                    return
                }
                // 将lob对象转换为域名结合式的url
                let blobUrl = window.URL.createObjectURL(res.data)
                let link = document.createElement('a')
                document.body.appendChild(link)
                link.style.display = 'none'
                link.href = blobUrl
                // 设置a标签的下载属性，设置文件名及格式，后缀名最好让后端在数据格式中返回
                var now = getNowFormatDate();
                link.download = recordId + '_' + now + "." + filePath.substring(filePath.length - 3);
                // 自触发click事件
                link.click()
                document.body.removeChild(link)
                window.URL.revokeObjectURL(blobUrl);
            })
        }


        if (obj.event === 'downloadEvent') {
            let index = layer.open({
                type: 0, // 0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                title: '提示',
                content: '确定将继续',
                icon: 3,
                area: 'auto',
                btn: ['确定', '取消'],
                btnAlign: 'c',
                closeBtn: 2,
                time: 0, // 默认：0 不会自动关闭
                resize: false,
                btn1: function () {
                    layer.close(index);
                    let url = '/work/modify/callRecord/download/' + (obj.data.finishTime.replace(/[^0-9]/ig, ""));
                    $.ajax({
                        type: "GET",
                        async: false,
                        url: url,
                        dataType: "json",
                        contentType: "application/json",
                        success: function (res) {
                            if (res.status === 200) {
                                layer.msg('提交下载任务成功，下载正在进行中，预计等待1-2分钟。请不要重复提交！！！');
                                // obj.del();
                            } else {
                                layer.msg('提交下载任务失败：' + res.message);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.msg('提交下载任务异常:' + errorThrown);
                        }
                    });
                },
                btn2: function () {
                    return true;
                }
            });
        }

    });

    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        return year + seperator1 + month + seperator1 + strDate;
    }

    /**
     * 初始化页面
     */
    function initPage() {
        // 渲染表格
        renderCallRecordListTable(callRecordListContainer);

        renderWorkingRecordListTable(workingRecordListContainer);
    }

    function init() {
        initPage();
        initEvent();
    }

    $(function () {
        init();
    });

    exports('oms_work_modify_callrecord');
});
